package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.service.WmNewsService;
import org.springframework.stereotype.Service;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    //内容列表全查
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //判断参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查分页参数
        dto.checkParam();
        //判断是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //创建分页条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getUserId,user.getId());//根据登录的用户id查询
        queryWrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());//根据文章状态查询
        queryWrapper.like(dto.getKeyword()!=null,WmNews::getTitle,dto.getKeyword());//根据关键字模糊查询
        queryWrapper.eq(dto.getChannelId()!=null,WmNews::getChannelId,dto.getChannelId());//根据频道Id查询
        //根据起止时间查询
        queryWrapper.between(dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null,WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());

        //创建Page对象
        Page pageInfo = new Page(dto.getPage(), dto.getSize());
        //实现分页
        Page page = page(pageInfo, queryWrapper);
        //结果封装
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    //删除文章
    @Override
    public ResponseResult delNews(Integer id) {
        //判断参数
        if (id==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id查询
        WmNews wmNews = getById(id);
        //判断状态是否已上架
        if (WmNews.Status.PUBLISHED.equals(wmNews.getStatus())){//已上架
            //返回不能删除的信息
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章已上架，请下架后再删除");
        }else {//未上架
            //执行删除并返回结果
            removeById(id);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }


}
